//
//  AppUpdate.swift
//  Lease_IOS
//
//  Created by Mr.wang on 2018/12/20.
//  Copyright © 2018 Mr.wang. All rights reserved.
//

import UIKit
import Moya
import HandyJSON
import RxSwift

class AppUpdate: NSObject {
    
    static let shared = AppUpdate()
    
    let appStoreProvider = MoyaProvider<APPStoreApiManager>()
    
    func checkUpdate() {
        appStoreProvider.rx.request(.checkUpdate)
            .jsonDictionary()
            .map{ UpdateModel.deserialize(from: $0) }
            .map{ $0?.results.first }
            .filterNil()
            .subscribe(onNext: { [unowned self] (result) in
                let version = self.currentVersion()
                let appSroreHasUpdate = result.version.compare(version) == .orderedDescending
                if appSroreHasUpdate {
                    self.showUpdate("https://itunes.apple.com/us/app/id" + APPConfig.appStoreId,
                                    releaseNotes: result.releaseNotes)
                }
            }).disposed(by: rx.disposeBag)
    }
    
    func showUpdate(_ url: String, releaseNotes: String) {
        let alert = UIAlertController.init(title: "版本更新".localized, message: releaseNotes, preferredStyle: .alert)
        alert.addAction(UIAlertAction.init(title: "取消".localized, style: .cancel, handler: nil))
        alert.addAction(UIAlertAction.init(title: "确定".localized, style: .default, handler: { (_) in
            guard let appStoreUrl = URL.init(string: url) else { return }
            UIApplication.shared.open(appStoreUrl, options: [:], completionHandler: nil)
        }))
        UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
    }
    
    func currentVersion() -> String {
        guard let info = Bundle.main.infoDictionary,
            let version = info["CFBundleShortVersionString"] as? String else {
                return ""
        }
        return version
    }
    
}

struct UpdateModel: HandyJSON {
    var resultCount : Int = 0
    var results = [UpdateResultModel]()
}

struct UpdateResultModel: HandyJSON {
    var trackViewUrl : String = ""
    var version : String = ""
    var releaseNotes : String = ""
}
